package com.shiliuzi.www.util.userUtil;

import com.shiliuzi.www.pojo.bo.UserInfoBo;
import com.shiliuzi.www.util.CommonUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Data
@Component
public class JWTUtil {

    @Resource
    private CommonUtil commonUtil;

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.header}")
    private String header;

    @Value("${jwt.expire.accessToken}")
    private Integer accessTokenExpire;

    @Value("${jwt.expire.refreshToken}")
    private Integer refreshTokenExpire;

    /**
     * 生成token信息
     * @param userInfoBo
     * @param nowDate
     * @param expireDate
     * @return
     */
    public String createToken(UserInfoBo userInfoBo, Date nowDate, Date expireDate) {
        return Jwts.builder()
                .setHeaderParam("typ","JWT")
                .setSubject("LG-"+userInfoBo.getRole())
                .setClaims(commonUtil.mapConverter(userInfoBo))
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
    }

    /**
     * 刷新令牌有效期
     * @param refreshToken
     * @param nowDate
     * @param expireDate
     * @return
     */
    public String refreshToken(String refreshToken, Date nowDate, Date expireDate) {
        return createToken(getUserInfo(refreshToken)
                ,nowDate
                ,expireDate);
    }

    public boolean verifyToken(String token) {
        Map<String,Object> body = Jwts.
                                    parser().
                                    setSigningKey(secret).
                                    parseClaimsJws(token).getBody();
        if(body == null || body.size()==0) return false;
        return true;
    }

    /**
     * 获取用户信息
     * @param token
     * @return
     */
    public UserInfoBo getUserInfo(String token) {
        return commonUtil.objectConverter(
                Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody(), UserInfoBo.class);
    }

    /**
     * 获取用户角色，进行rbac
     * @param token
     * @return
     */
    public String getUserRole(String token) {
        return getUserInfo(token).getRole();
    }

    /**
     * 获取用户学号，进行存储redis
     * @param token
     * @return
     */
    public String getUserNumber(String token) {
        return getUserInfo(token).getNumber();
    }
}
